package com.ych.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ych.beans.Message;
import com.ych.beans.PipeModel;
import com.ych.dao.PipeModelDao;
import com.ych.service.PipeModelService;
import com.ych.util.FilePathUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;

@Service
public class PipeModelServiceImpl implements PipeModelService {
    @Autowired
    PipeModelDao dao;
    @Autowired
    StringRedisTemplate temp;

    //上传文件暂存至临时文件夹中，确认操作完成后再转至目标文件夹
    @Override
    public Message upload(MultipartFile file) {

        //需要修改文件存储路径去com.ych.util.FilePathUtil类中修改savePath变量值
        String tempFilePath = FilePathUtil.Temp_Save_Path;
        String fileName = file.getOriginalFilename();
        File tempSaveFile = new File(tempFilePath);
        //创建临时文件夹
        if (!tempSaveFile.exists()){
            tempSaveFile.mkdir();
        }
        tempSaveFile = new File(tempFilePath.concat(fileName));
        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(),tempSaveFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new Message(true,fileName,null);
    }

    @Override
    public Message addPipeModel(PipeModel pipe) {
        final Message message = new Message();
        boolean flag = dao.addPipeModel(pipe);
        message.setSuccess(flag);
        if (flag){
            message.setMsg("添加成功");
            saveType(pipe);
        }else {
            message.setMsg("添加失败");
        }
        return message;
    }

    @Override
    public Message updatePipeModel(PipeModel pipe) {
        final Message message = new Message();
        PipeModel oldPipeModel = dao.selectPipeModel(null,pipe.getId()).get(0);
        boolean flag = dao.updatePipeModel(pipe);
        message.setSuccess(flag);
        if (flag){
            message.setMsg("修改成功");
            //新旧pipeName和pipeType对比，如果变化转移至新路径并删除原路径文件
            if (!(oldPipeModel.getPipeNumber()+oldPipeModel.getPipeName()).
                    equals(pipe.getPipeNumber()+pipe.getPipeName())){
                File oldFile = new File(FilePathUtil.Save_Path + oldPipeModel.getPipeName() + "/" + oldPipeModel.getPipeNumber());
                File newFile = new File(FilePathUtil.Save_Path + pipe.getPipeName() + "/" + pipe.getPipeNumber());

                try {
                    FileUtils.copyDirectory(oldFile,newFile);
                    //如果名字一致就删除子文件夹
                    if (oldPipeModel.getPipeName().equals(pipe.getPipeName())){
                        deleteFile(FilePathUtil.Save_Path + "/" + oldPipeModel.getPipeName() + "/" + oldPipeModel.getPipeNumber());
                    }else{
                        //名字不一致就删除以此名字命名的文件夹
                        deleteFile(FilePathUtil.Save_Path + "/" + oldPipeModel.getPipeName());
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            saveType(pipe);
        }else {
            message.setMsg("修改失败");
        }
        return message;
    }

    @Override
    public Message deletePipeModel(Integer id) {
        Message message = new Message();
        boolean flag = false;
        List<PipeModel> pipes = dao.selectPipeModel(null, id);
        PipeModel pipe;
        if (!pipes.isEmpty()){
            pipe = pipes.get(0);
        }else {
            return new Message(false,"不存在该管道模型",null);
        }
        String savePath = FilePathUtil.Save_Path + pipe.getPipeName();
        boolean isDeleted = deleteFile(savePath);
        if (isDeleted){
            flag = dao.deletePipeModel(id);
        }
        message.setSuccess(flag);
        if (flag){
            message.setMsg("删除成功");
        }else {
            message.setMsg("删除失败 ");
        }
        return message;
    }

    @Override
    public Message selectPipeModel(Integer pageNo, String key) {
        Message message = new Message();
        if(pageNo!=null){
            PageHelper.startPage(pageNo, 8);
        }
        List<PipeModel> list=dao.selectPipeModel(key,null);
        final PageInfo<PipeModel> objectPageInfo = new PageInfo<>(list);
        message.setSuccess(true);
        if(!list.isEmpty()){
            message.setObj(objectPageInfo);
        }
        return message;
    }

    //判断已经上传的文件类型
    private void saveType(PipeModel pipe){
        //将临时文件夹的文件保存至存档文件夹
        if (pipe.getPipePic() != null && !pipe.getPipePic().equals("")){
            saveFile(pipe.getPipePic(), pipe,"pic");
        }
        if (pipe.getPipeManual() != null && !pipe.getPipeManual().equals("")){
            saveFile(pipe.getPipeManual(),pipe,"manual");
        }
        if (pipe.getPipeIntroduce() != null && !pipe.getPipeIntroduce().equals("")){
            saveFile(pipe.getPipeIntroduce(),pipe,"introduce");
        }
    }

    //将临时文件存储到目标文件夹
    private void saveFile(String fileName, PipeModel pipe, String fileType){
        File tempFile = new File(FilePathUtil.Temp_Save_Path.concat(fileName));
        String savePath = FilePathUtil.Save_Path + pipe.getPipeName() + "/" + pipe.getPipeNumber();
        File saveFileDir = new File(savePath);
        //文件夹不存在则创建
        if (!saveFileDir.exists()){
            saveFileDir.mkdirs();
        }
        //考虑到后续修改时上传文件，目标文件如果存在则删除
        File saveFile = new File(savePath + "/" + fileName);
        if (saveFile.exists()){
            saveFile.delete();
        }
        //将临时文件复制到目标文件夹中
        try {
            FileUtils.copyFileToDirectory(tempFile,new File(savePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //删除临时保存文件
        tempFile.delete();
    }

    //删除文件夹
    private boolean deleteFile(String filePath) {
        boolean flag = true;
        File file = new File(filePath);
        if (file.isFile()){  //判断是否为文件，是，则删除
            flag = file.delete();
        }
        else{ //不为文件，则为文件夹
            String[] childFilePath = file.list();//获取文件夹下所有文件相对路径
            for (String path:childFilePath) {
                deleteFile(file.getAbsoluteFile()+"/"+path);//递归，对每个都进行判断
            }
            flag = file.delete();
        }
        return flag;
    }
}
